package user

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/enums"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/framework/model/entity"
	"gitee.com/bobo-rs/idea-space-framework/framework/service"
	"gitee.com/bobo-rs/idea-space-framework/pkg/core/services/login"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/errors/gerror"
)

// ValidateSmsCaptchaLogin 用户授权短信验证码登录并校验验证码
func (u *sUser) ValidateSmsCaptchaLogin(ctx context.Context, in model.UserOauthSmsLoginItem) (*model.UserOauthLoginDetailItem, error) {
	var (
		err    error
		detail = &model.UserOauthLoginDetailItem{}
	)

	if !utils.IsMobile(in.Mobile) {
		return nil, gerror.New(`手机号格式错误`)
	}

	// 验证码验证
	err = service.SmsTpl().ValidateCode(ctx, in.Mobile, in.Code)
	if err != nil {
		return nil, err
	}

	// 获取账户信息
	if err = u.ProcessDetailByMobile(ctx, in.Mobile, &detail.User); err == nil && detail.User != nil {
		// 老用户，直接返回
		return detail, nil
	}

	// 手机号不存在，创建新用户
	newUserDetail := model.UserSaveUserDetailItem{
		User: &entity.User{
			Mobile: in.Mobile,
		},
	}
	u.processNewUserDetail(ctx, &newUserDetail)
	newUserDetail.Id, err = u.SaveUser(ctx, newUserDetail)
	if err != nil {
		return nil, err
	}

	// 返回用户信息
	detail.User = newUserDetail.User
	detail.Status = enums.UserLoginStatusSP // 提醒未设置密码
	return detail, nil
}

// UserLoginSendSmsCaptcha 用户认证登录发送短信验证码
func (u *sUser) UserLoginSendSmsCaptcha(ctx context.Context, in model.UserLoginSendSmsCaptchaInput) error {
	// 验证解密签名
	item, err := service.Common().Verify(
		ctx, in.Sign, enums.SafeTagsSmsCaptcha, true,
	)
	if err != nil {
		return err
	}

	// 解密并验证手机号
	mobile, err := u.DecryptMobile(in.Mobile, item.Secret)
	if err != nil {
		return err
	}

	// 发送手机号
	return service.SmsTpl().SendCaptcha(ctx, mobile, enums.SmsAliasRegisterCaptcha)
}

// DecryptMobile 解密手机号
func (u *sUser) DecryptMobile(mobileCipher, secret string) (string, error) {
	// 解密手机号
	mobile, err := login.New().Decrypt(mobileCipher, secret)
	if err != nil {
		return "", err
	}

	// 是否手机号
	if !utils.IsMobile(mobile) {
		return "", gerror.New(`手机号格式错误`)
	}
	return mobile, nil
}
